package org.example.stdent.sqlsessionutil;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class sqlsessionutil {
    //被static修饰才能被静态代码块访问
    //成员变量整个类都可以访问到 在创建sqlsession对象时需要访问
    private static SqlSessionFactory sessionFactory;
    //读取配置文件
    static {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis.xml");
            //读取配置文件 找到在配置文件中注册的映射文件
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //构建者建造了工厂
            sessionFactory = builder.build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //获得SqlSession对象
    public  static SqlSession getSqlSession(){
        //工厂创建对象
        SqlSession sqlSession = sessionFactory.openSession();
        return sqlSession;
    }
    public static void closeSqlSession(SqlSession sqlSession){
        //关闭sqlsession
        if (sqlSession != null){
            sqlSession.close();
        }
    }


}
